<template>
  <q-previewImage v-show="isPreview" class="z-19000" ref="previewImage"
    :urls="[currentRecord.skuImageUrl || defaultImg]"></q-previewImage>
  <view class="order-page flex flex-col h-full box-border">
    <view class="sticky common-input pos-top-0 z-1 bg-#fff pb-10rpx">
      <up-input shape="circle" class="mx-10pt text-44pt" placeholder="搜索PO单号/产品名称/好达威SKU" prefixIcon="search"
        prefixIconStyle="color: #909399" @change="(val) => searchProduct(val)"></up-input>
      <CircleNewTab ref="circleTabRef" :circleTabOptions="tabOptions" @change="changeCircleTab"></CircleNewTab>
      <view class="pay-btn-box text-24rpx flex justify-end pr-24rpx" v-if="activeCircleTab === 2 && (paymentType === 1 || paymentType === 2)">
        <view v-if="isCheckPay">
          <up-button class="h-54rpx" type="success" size="mini" icon="checkmark-circle" iconColor="#00B42A"
            color="#00B42A" :plain="true" text="仅查看已付款" @click="handleCheckPay"></up-button>
        </view>
        <view v-else class="h-54rpx">
          <up-button type="primary" size="mini" :plain="true" text="仅查看已付款" color="#000"
            @click="handleCheckPay"></up-button>
        </view>
      </view>
    </view>
    <view v-if="!orderList.length" class="mt-168rpx w-320rpx m-auto  text-#999999">
      <img class="w-280rpx h-280rpx" :src="emptyImg">
      <view class="text-center">
        暂无数据
      </view>
    </view>
    <scroll-view class="flex-1 mb-200rpx" :scroll-y="true" style="min-height: 0;" :lower-threshold="50"
      @scrolltolower="refrash()">
      <up-collapse v-for="(order, index) in orderList" :key="index" value="orderList" accordion :border="false">
        <view :class="order.isTop ? 'top-style' : ''">
          <up-collapse-item>
            <template #title>
              <view class="common-product-list">
                <view v-if="order.isTop" class="flex">
                  <view><img class="w-32rpx h-32rpx" :src="topImg" alt="图片" /></view>
                  <view class="mx-16rpx text-24rpx font-700">置顶</view>
                  <view class="text-#F53F3F underline font-700 text-24rpx cursor-pointer"
                    @click="() => cancleTop(order.id)">取消置顶</view>
                </view>
                <view class="common-product-list-item">
                  <view class="common-product-list-item-left">
                    <view @click.stop="gotoDetail(order.id)">
                      <view class="flex items-center">
                        <view class="name underline underline-offset-4">
                          {{ order?.poNumber || '' }}
                        </view>
                        <view
                          v-if="order?.poState !== 6 && order?.poState !== 7 && (order?.paymentSign === 1 || order?.paymentSign === 2) && (order?.paymentType === 1 || order?.paymentType === 2)"
                          class="order-state flex items-center px-16rpx py-4rpx border-rd-11px text-#fff ml-8rpx text-24rpx"
                          style="background-color: #34C759;min-width: 104rpx;">
                          <up-icon name="star-fill" color="#fff" size="12"></up-icon>
                          {{ order?.paymentSign === 1 ? `已付款` : '已结清' }}
                        </view>
                      </view>
                      <view class="common-product-list-item-right">
                        {{ order?.poCurrency?.unitSymbol }}{{ thousandSeparatFormat(order?.poPrice || 0) }} 总计
                        {{ order?.poPcs || 0 }}
                      </view>
                    </view>
                  </view>
                  <view class="common-product-list-item-right" v-if="order?.createdTime">
                    {{ dayjs(order?.createdTime).format('YYYY/MM/DD HH:mm') }}
                  </view>
                </view>
              </view>
            </template>
            <view v-if="order?.skuInfoList.length" v-for="(item, idx) in order.skuInfoList" class="common-product-list"
              :key="idx">
              <view class="common-product-list-item">
                <img v-if="(order.poState === 2 || order.poState === 3 || order.poState === 10) && item.skuState === 8"
                  class="w-100rpx h-100rpx absolute right-100rpx -z-1" :src="yellowImg" alt="图片"
                  @click.stop="gotoDetail(order.id)" />
                <img v-if="(order.poState === 2 || order.poState === 3 || order.poState === 10) && item.skuState === 9"
                  class="w-100rpx h-100rpx absolute right-100rpx -z-1" :src="greenImg" alt="图片" />
                <img v-if="item.skuState === 7" class="w-100rpx h-100rpx absolute right-100rpx -z-1" :src="cancelImg"
                  alt="图片" @click.stop="gotoDetail(order.id)" />
                <view class="common-product-list-item-left ">
                  <img style="width: 80rpx; height: 80rpx; border-radius: 8rpx; margin-right: 16rpx;"
                    :src="item.skuImageUrl || defaultImg" @click="preview(item)" />
                  <view @click.stop="gotoDetail(order.id)">
                    <view class="name">
                      <view v-if="item?.purchaseType === 1" class="jz-tag">集</view>{{ item?.skuDescription || '' }}
                    </view>
                    <!-- <view class="flex items-start">
                    <view class="name">
                      {{ item?.skuDescription || '' }}
                    </view>
                    <span v-if="item.skuState === 8 || item.skuState === 9"
                      :class="`font-800 px-10rpx py-4rpx  border-rd-11px text-white vertical-middle ${skuStateTextColorMap.get(item.skuState)}`">
                      {{ skuStateTextMap.get(item.skuState) }}</span>
                  </view> -->
                    <view class="sub-name">
                      好达威SKU:{{ item.skuCode || '' }}
                    </view>
                    <view v-if="item.supplierSkuCodes?.filter((code: string) => !!code)?.length" class="sub-name">
                      商家SKU:{{ item.supplierSkuCodes.join(',') || '' }}
                    </view>
                  </view>
                </view>
                <view class="common-product-list-item-right">
                  <view>
                    {{ order?.poCurrency?.unitSymbol }}{{ thousandSeparatFormat(item?.skuUnitPrice || 0) }}x{{
                      item?.skuPcs || 0 }}
                  </view>
                  <view class="greenText font-700"
                    v-if="(order.poState === 2 || order.poState === 3 || order.poState === 10) && item.deliveryCount > 0">
                    （已发{{ item.deliveryCount }}）
                  </view>
                </view>
              </view>
            </view>
          </up-collapse-item>
        </view>

      </up-collapse>
    </scroll-view>
  </view>
  <CustomTabbar page="orderList"></CustomTabbar>
</template>

<script setup lang="ts">
import { poManageQueryPoInfo, poManageQueryPoStateCount, poManageCancelIsTop } from "@/genapi/poManage";
import { orderTabOptions } from "@/utils/options";
import { thousandSeparatFormat } from "@/utils/utils";
import { debounce } from '@antfu/utils'
import emptyImg from "@/static/empty.png"
import defaultImg from "@/static/default.png"
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { useSupplierStore } from '@/store/index'
import dayjs from "dayjs"
import greenImg from '@/static/greenDelivery.svg'
import yellowImg from '@/static/yellowReissue.svg'
import cancelImg from '@/static/cancel.svg'
import topImg from '@/static/top.svg'
// import { skuStateTextColorMap, skuStateTextMap } from "@/utils/options"

const loaded=ref(false)
const circleTabRef = ref(null)
const isCheckPay = ref(false)
const supplierStore = useSupplierStore()
const paymentType = computed(() => {
  return supplierStore.supplierInfo?.paymentType
})
const previewImage = ref()
const isPreview = ref(false)
const currentRecord = ref({})
onLoad((options) => {
  uni.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline']
  })
})
onShow(async(options) => {
  const tab = await uni.getStorageSync('orderTab')
  if(tab&&loaded.value){
    nextTick(() => {
      circleTabRef.value.circleTabChange(Number(tab))
      uni.setStorageSync('orderTab', '')
    })
  }
  else if (supplierStore.waitSend) {
    circleTabRef.value.circleTabChange(2)
    changeCircleTab(2)
    nextTick(() => {
      supplierStore.setWaitSend(false)
    })
  }
})
onShareAppMessage(() => {
  return {
    title: '好达威供应商系统',
    path: '/pages/index/index',
  }
})
onShareTimeline(() => {
  return {
    title: '好达威供应商系统',
    path: '/pages/index/index',
  }
})

const tabOptions = ref(orderTabOptions)
const activeCircleTab = ref(1)
const orderList = ref([])
const hasNext = ref<boolean>(true)
let apiParams: any = {
  page: 1,
  pageSize: 10,
  poState: 1
}
const fetchList = debounce(500, getOrderList)
async function handleCheckPay() {
  isCheckPay.value = !isCheckPay.value
  apiParams.page = 1
  apiParams.paymentSign = isCheckPay.value ? [1, 2] : []
  await fetchList()
}
// onLoad((query) => {
//   defaultTab.value = +query?.poState || 1
// })
function gotoDetail(id: string) {
  uni.navigateTo({
    // url: `/pages/editProduct/index?id=${item.id}`
    url: `/pages/orderDetail/index?id=${id}`,
  })
}
// 预览图片
async function preview(item: any) {
  currentRecord.value = item
  isPreview.value = true
  await nextTick(() => {
    previewImage.value.open(item.skuImageUrl); // 传入当前选中的图片地址(小程序必须添加$nextTick，解决组件首次加载无图)
  })
}
async function cancleTop(id: string) {
  const { data } = await poManageCancelIsTop({ poId: id })
  if (data?.code !== 200) return
  fetchList()
}
async function gotoLogin() {
  const isNoLogin = await uni.getStorageSync('isNoLogin')
  if (isNoLogin) {
    uni.navigateTo({
      url: '/pages/login/index'
    })
    return false
  } else {
    return true
  }
}

function search(val: string) {
  apiParams.searchText = val
  orderList.value.length = 0
  apiParams.page = 1
  getOrderList()
}
const searchProduct = debounce(500, search)

async function getTabCount() {
  const params = {
    searchText: apiParams.searchText,
    paymentSign: apiParams.paymentSign
  }
  const { data } = await poManageQueryPoStateCount(params)
  if (data?.code !== 200) return
  const result = data.data
  tabOptions.value.map((item: any) => {
    const tab = result.find((state: any) => item.value === state.poState)
    item.count = tab?.count || 0
    return item
  })
}
async function getOrderList() {
  const isLogin = await gotoLogin()
  if (isLogin) {
    getTabCount()
    const { data } = await poManageQueryPoInfo(apiParams)
    if (data?.code !== 200) return
    else {
      const result = data.data
      if (apiParams.page === 1) orderList.value.length = 0
      if (result.tableData)
        orderList.value = orderList.value.concat(result.tableData)
      hasNext.value = result?.hasNext || false
    }
  }
}

// 触底刷新
const refrash = debounce(500, tolower)
async function tolower() {
  if (hasNext.value) {
    //页数累加
    apiParams.page++
    getOrderList()
  }
}
// tab切换
const changeCircleTab = (val: number) => {
  if (val === 2) {
    apiParams.paymentSign = isCheckPay.value ? [1, 2] : []
  } else {
    apiParams.paymentSign = undefined
  }
  activeCircleTab.value = val
  apiParams.poState = val
  orderList.value.length = 0
  apiParams.page = 1
  getOrderList()
}

onMounted(async () => {
   const tab  = await uni.getStorageSync('orderTab')
  const isNoLogin = await uni.getStorageSync('isNoLogin')
  if (isNoLogin) return
  loaded.value = true
    nextTick(() => {
      circleTabRef.value.circleTabChange(Number(tab?tab:1))
      uni.setStorageSync('orderTab', '')
    })
})
</script>
<style scoped lang="scss">
.top-style {
  border: 2px solid #1a5fa9;
  border-radius: 10rpx;
  margin: 26rpx 30rpx;
}

.common-product-list-item-left {
  .underline {
    text-decoration: underline;
  }
}

.jz-tag{
  width: 40rpx;
  height: 40rpx;
  display: inline-block;
  border-radius: 50%;
  background: #fff;
  border: 1px solid #e50000;
  color: #e50000;
  text-align: center;
  margin-right: 4px;
}
</style>
